/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package protsc;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.io.OutputStream;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.nio.file.StandardOpenOption.*;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Will
 */
public class ProtSc extends Application {

    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                int protNum = 0;
                int protGroupNum = 0;
                int protUnmapNum = 0;
                Map protGroup = new HashMap<String, String>();
                Map protIndex = new HashMap<String, String>();
                Map protUnmap = new HashMap<String, Integer>();
                List<String> list =  new LinkedList<String>();
                for (int k = 1; k <= 4; k++) {
                    Path file = Paths.get("C:\\Users\\Will\\Desktop\\test-files", "prot-" + k + ".prot.xls");

                    try (BufferedReader reader = Files.newBufferedReader(file)) {
                        String line = null;
                        String regex = "(\\d+)([a-z]+)";
                        String decoyReg = "(DECOY_).+";

                        while ((line = reader.readLine()) != null) {
                            if (line.isEmpty()) {
                                continue;
                            }
                            String[] stringArray = line.split("\t");
                            String entryNo = stringArray[0];
                            String groupProb = stringArray[1];
                            if (groupProb.contains("group")) {
                                continue;
                            }
                            if (Double.parseDouble(groupProb) < 0.9) {
                                continue;
                            }
                            String protName = stringArray[2];
                            // this is a protein group 
                            if (entryNo.matches(regex)) {
                                Pattern pattern = Pattern.compile(regex);
                                Matcher matcher = pattern.matcher(entryNo);
                                while (matcher.find()) {
                                    //System.out.println(matcher.group(2));
                                    entryNo = matcher.group(1);
                                }
                            } else {
                                //System.out.println(entryNo);
                            }
                            String[] protNames = protName.split(",");
                            for (int i = 0; i < protNames.length; i++) {
                                String pn = protNames[i];
                                if (pn.matches(decoyReg)) {
                                    //System.out.println("#"+pn);
                                    continue;
                                }
                                if (protIndex.containsKey(pn)) {
                                    //continue;
                                } else {
                                    String protRep;
                                    if (protGroup.containsKey(entryNo)) {
                                        protRep = (String) protGroup.get(entryNo);
                                    } else {
                                        protGroup.put(entryNo, pn);
                                        protRep = pn;
                                        protGroupNum++;
                                    }
                                    protIndex.put(pn, protRep);
                                    //System.out.println(pn + "->" + protRep);
                                    protNum++;
                                }

                                //System.out.println(pn + "->" + protRep);
                                //protNum ++;
                            }
                            //System.out.println("#"+line);
                        }
                    } catch (IOException e) {
                        System.out.print(e);
                    }
                    //System.out.println("Hello World!");
                    System.out.println("Group:" + protGroupNum + ";Prot:" + protNum);
                }
                Path file = Paths.get("C:\\Users\\Will\\Desktop\\test-files", "iPRG2015-skyline.csv");

                try (BufferedReader reader = Files.newBufferedReader(file)) {
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        if (line.isEmpty()) {
                            continue;
                        }
                        String[] stringArray = line.split(",");
                        String modifiedPeptide = stringArray[0];
                        String protein = stringArray[2];
                        if (protein.contains("Protein")){
                            continue;
                        }
                        
                        line = line.replace("-A", "_A");
                        if (protIndex.containsKey(protein)){
                            String newProtein = (String) protIndex.get(protein);
                            line = line.replace(protein, newProtein);
                            //System.out.println(line);
                            list.add(line+"\n");
                        }else{
                            //System.out.println("WARN: protein "+protein+" is not found previously!");
                            if (protUnmap.containsKey(protein)){
                                protUnmap.put(protein, (Integer) (protUnmap.get(protein)) + 1);
                            }else{
                                protUnmap.put(protein, 1);
                            }
                        }
                        
                    }
                    System.out.println("Unmap protein: "+ protUnmap.size());
                    Iterator it = protUnmap.entrySet().iterator();
                    while(it.hasNext()){
                        Map.Entry mapEntry = (Map.Entry) it.next();
                        System.out.println("key: " + mapEntry.getKey() + ", value:" + mapEntry.getValue());
                    }
                } catch (IOException ex) {
                    Logger.getLogger(ProtSc.class.getName()).log(Level.SEVERE, null, ex);
                }
//                
//                BufferedWriter out = null;
                try {
                    FileWriter fstream = new FileWriter("D:\\out.txt", true);
//                    for (int i = 0; i < list.size(); i++) {
//                        fstream.write(list.get(i) + "\n");
//                    }
                    for (String line: list){
                        fstream.write(line);
                    }
                    fstream.flush();
                    fstream.close();
                } catch (IOException ex) {
                    Logger.getLogger(ProtSc.class.getName()).log(Level.SEVERE, null, ex);
                }

                
            }
        });

        StackPane root = new StackPane();
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}
